package com.atguigu.gulimall.member.config;

import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 满超
 * @date 2020/06/26
 * 远程调用，带上老的cookie。
 * 请求拦截器，每一次请求拦截
 **/
@Configuration
public class FeignInterceptConfig {

    /**
     * 解决远程请求，请求头丢失问题
     * @return
     */
    @Bean
    public RequestInterceptor requestInterceptor(){
        return requestTemplate -> {
            //拿到刚进来的请求
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

            if (requestAttributes != null) {
                HttpServletRequest request = requestAttributes.getRequest();//老请求
                String cookie = request.getHeader("Cookie");

                //给新请求同步老请求的cookie
                requestTemplate.header("Cookie", cookie);
            }
        };
    }
}
